#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "load_jobs.h"
#include "linkedList.h"

#define NDEBUG

// int *pc is the program counter

struct jobNode *create_job_linked_list(char *input_file_path, int *pc) {

    struct jobNode *head = NULL;
    struct jobNode *temp = NULL;
    char *token, *cmd;
    char string[STRING_BUFFER_MAX];
    int arrival_time, duration, i = 0;
    FILE *fp;

    if ((fp = fopen(input_file_path,"r")) == NULL) {
        perror("job file open error ");
        exit(-1);
    }

    while(!feof(fp)) {
        if(fgets(string,STRING_BUFFER_MAX - 1,fp)!=NULL){
            token = strtok(string,"\t");
                while (token != NULL){
                    switch (i++)
                    {
                    	case 0:
                            arrival_time = atoi(token);
                    		break;

                        case 1:
                            cmd = token;
                    		break;

                        case 2:
                            duration = atoi(token);
                    		break;

                    	default:
                            printf("ERROR @ strtok switch, i != 0,1,2 \n");
                            exit(-1);
                    		break;
                    }
                    token = strtok(NULL,"\t");
                }
        if (temp == NULL){
        	temp = createNode(arrival_time,cmd,duration);
        	head = temp;
        } else {
            temp->next = createNode(arrival_time,cmd,duration);
            temp = temp->next;
            }
        i = 0;
        (*pc)++;
        }
    }
    fclose(fp);
    return head;
}
